var http = require('http')
var mime = require('mime')
var fs = require('fs')
var path = require('path')

var cache = {}

// 发送404
function send404(res) {
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.write('Error 404: resource not found')
    res.end()
}

// 发送文件
function sendFile(res, data, abs) {
    res.writeHead(200, { 'Content-Type': mime.lookup(path.basename(abs)) })
    res.end(data)
}

// 提供静态资源服务
function serverStatic(res, path, cache) {
    // 判断缓存中有没有该文件
    if (cache[path]) {
        sendFile(res, cache[path], path)
    } else {
        // 判断是否存在该文件
        fs.exists(path, function(exists) {
            if (exists) {
                fs.readFile(path, function(err, data) {
                    if (err) {
                        send404(res)
                    } else {
                        cache[path] = data
                        sendFile(res, data, path)
                    }
                })
            } else {
                send404(res)
            }
        })
    }
}

var server = http.createServer(function(req, res) {
    var path;
    var abs;
    if (req.url === '/') {
        path = 'public/index.html'
    } else {
        path = 'public' + req.url
    }
    abs = './' + path

    serverStatic(res, path, cache)
})

server.listen(3000, function() {
    console.log("Server listening on port 3000.");
});

var chatServer = require('./lib/chat_server');
chatServer.listen(server);
